#!/bin/sh

defaultBranchArr=("dev" "test" "uat" "master")

curBranch=$(git rev-parse --abbrev-ref HEAD)
preBranch="$curBranch"

# echo "当前分支为：$curBranch"

flag=0
curBranchArr=()

# echo "flag:  $flag"

function myEcho(){
	echo -e "\033[${2}m${1}\033[0m"
}

for item in "${defaultBranchArr[@]}"; do
	if (( flag )); then
		curBranchArr+=($item)
		# echo "11 ${curBranchArr[@]}"
	elif test $item=$curBranch; then
		flag=1
	#	curBranchArr+=($item)
		# echo "22 ${curBranchArr[@]}"
	else
		myEcho "无了" 35
	fi
done

if (( "${#curBranchArr[@]}" > 0 )); then
	myEcho "当前需要合并的分支为：${curBranchArr[@]}" 33
	myEcho "开始分别合并分支。。。" 33

	for branch in "${curBranchArr[@]}"; do
		git checkout "$branch"

		myEcho "当前分支为：$branch" 34
		myEcho "前置分支为：$preBranch" 34
		
		git pull origin "$branch"

		time=$(date '+%Y-%m-%d %H:%M:%S')
		author=$(git log -1 --no-merges --pretty=format:'%an')
		message="$preBranch merge into $branch  at $time  by $author"
		
		git merge "$preBranch" --no-ff -m "$message"
		
		git push origin "$branch"
		myEcho "分支 $branch 已合并完成！！" 32
		myEcho "提交信息：$message" 32
		preBranch="$branch"
	done
	git checkout "$curBranch"
	myEcho "提交成功！！分支已切换到$curBranch" 32
else
	myEcho "不用合并了" 32
fi
